package org.jeecg.modules.demo.jxcx.controller;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.modules.demo.jxcx.Utils.HttpUtils;
import org.jeecg.modules.demo.jxcx.Utils.R;
import org.jeecg.modules.demo.jxcx.service.ITbPayOrdidService;
import org.jeecg.modules.demo.jxcx.service.JxcUserService;
import org.jeecg.modules.demo.jxcx.service.OutpatientService;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping({"wxpay"})
public class WxPayController {

    private static Logger logger = LoggerFactory.getLogger(WxPayController.class);
    @Autowired
    private OutpatientService outpatientService;
    @Autowired
    private JxcUserService jxcUserService;

    private static String apiV3Key = "ZwXH6A8XH5sJTWFJfPJPbS0mQ8x5bhr6";
    @Autowired
    private ITbPayOrdidService iTbPayOrdidService;

    @PostMapping("/getWxPay")
    @ApiOperation("获取调用自费微信支付的参数")
    public R getWxPay(@RequestBody JSONObject params) {
        R result = null;
        try {
            result = outpatientService.getWxPay(params);
        } catch (Exception e) {
            result = new R().error(e.getMessage());
        }
        return result;
    }
    /**
     * 被动查询
     */
    @PostMapping("/Payresult")
    @ApiOperation("自费支付异步通知接口")
    public R<String> Payresult(@RequestBody JSONObject settlementData) throws Exception {
        logger.info("接收到自费支付异步通知 = " + settlementData);
        String eventType = settlementData.getString("event_type");
        if ("TRANSACTION.SUCCESS".equals(eventType)) //支付成功回调
            logger.info(">>>>>微信支付成功<<<<<");
        AesUtil aesUtil = new AesUtil(apiV3Key.getBytes());
        JSONObject resource = settlementData.getJSONObject("resource");
        String data = aesUtil.decryptToString(resource.getString("associated_data").getBytes(), resource.getString("nonce").getBytes(), resource.getString("ciphertext"));
        logger.info("解密结果：" + data);

        JSONObject json = JSONObject.parseObject(data);
        String out_trade_no = json.getString("out_trade_no");
        iTbPayOrdidService.savepayjson(out_trade_no,data);
        String xiadandata = iTbPayOrdidService.selectdataByOutTradeNo(out_trade_no);
        String state = iTbPayOrdidService.selectstateByOutTradeNo(out_trade_no);
        JSONObject xiadan = JSONObject.parseObject(xiadandata);

        if (!state.equals("2")){
            if (json.getString("attach").contains("续费")){
                jxcUserService.exdate(xiadan);
            } else if (json.getString("attach").contains("开通")){
                jxcUserService.add(xiadan);
            }
            iTbPayOrdidService.updatestate("2",out_trade_no);
        }

        return new R<>();

    }
    @PostMapping("/getWxPayRefund")
    @ApiOperation("调用自费微信支付退费")
    public R getWxPayRefund(@RequestBody JSONObject params) {
        R result = null;
        try {
            result = new R().ok(outpatientService.getWxPayRefund(params));
        } catch (Exception e) {
            result = new R().error(e.getMessage());
        }
        return result;
    }
    /**
     * 被动查询
     */
    @PostMapping("/PayRefundresult")
    @ApiOperation("自费退费异步通知接口")
    public R<String> PayRefundresult(@RequestBody JSONObject settlementData) throws Exception {
        logger.info("接收到自费退费异步通知 = " + settlementData);
        String eventType = settlementData.getString("event_type");
        if ("REFUND.SUCCESS".equals(eventType)) //支付成功回调
            logger.info(">>>>>微信退费成功<<<<<");
        AesUtil aesUtil = new AesUtil(apiV3Key.getBytes());
        JSONObject resource = settlementData.getJSONObject("resource");
        String data = aesUtil.decryptToString(resource.getString("associated_data").getBytes(), resource.getString("nonce").getBytes(), resource.getString("ciphertext"));
        logger.info("解密结果：" + data);
        JSONObject json = JSONObject.parseObject(data);
        String out_trade_no = json.getString("out_trade_no");
        iTbPayOrdidService.updateRefundjson(out_trade_no,data);
        return new R<>();
    }
    @PostMapping("/getWxPayState")
    @ApiOperation("主动查询自费微信支付的状态")
    public R getWxPayState(@RequestBody JSONObject params) {
        R result = null;
        try {
            result = outpatientService.getWxPayState(params);
        } catch (Exception e) {
            result = new R().error(e.getMessage());
        }
        return result;
    }
    @PostMapping("/getphone")
    @ResponseBody
    public R getphone(@RequestBody JSONObject params) {
        R result = null;
        try {
            String result1 = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1d9ab11ee22e9e8f&secret=4dbd20a4658d477acd71dd8be3152612");
            JSONObject json1 = JSONObject.parseObject(result1);
            String access_token = json1.getString("access_token");
            JSONObject param = new JSONObject();
            param.put("code", params.getString("code"));
            String result2 = HttpUtils.sendPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token, param);
            JSONObject result2_2 = JSONObject.parseObject(result2);
            System.out.println(result2_2.getInteger("errcode") == 0);
            if (result2_2.getInteger("errcode") == 0) {
                System.out.println(result2_2.getJSONObject("phone_info").getString("purePhoneNumber"));
                JSONObject re = new JSONObject();
                re.put("purePhoneNumber", result2_2.getJSONObject("phone_info").getString("purePhoneNumber"));
                return new R().ok(re);
            }
            throw new Exception("手机号认证异常");
        } catch (Exception e) {
            e.printStackTrace();
            result = new R().error(e.getMessage());
        }
        return result;
    }
}
